import { ReactElement, useState, useEffect, useRef, RefObject } from 'react'
import { CaseSchema } from '@components/schema/caseSchema'
import { Modal, Form, Row, Col, Input, TreeSelect, DatePicker, Select, FormInstance, message } from 'antd'
import { getTreeRequest, getPersonList, updateCaseRequest } from './ajax'
import { DataNode } from 'rc-tree-select/lib/interface'
import { awaitWrap } from '@src/assets/js/tool'
import UnitNumberInput from '@components/unitNumberInput'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import moment, { Moment } from 'moment'

const { Item } = Form
const { Option } = Select

// 初始化案由树
async function initTree (setTreeData: (v: DataNode[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getTreeRequest())
  if (e === null && d !== null) {
    setTreeData(d)
  }
}

// 初始化员工列表
async function initPersonList (setPersons: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonList())
  if (e === null && d instanceof Array) {
    setPersons(d)
  }
}

function initForm (formRef: RefObject<FormInstance>, data: CaseSchema | null): void {
  const c = formRef.current
  if (c === null || data === null) {
    return undefined
  }
  const o: { [k: string]: any } = { ...data }
  if (typeof data.accept_datetime === 'string') {
    o.accept_datetime = moment(data.accept_datetime)
  }
  if (typeof data.docket_datetime === 'string') {
    o.docket_datetime = moment(data.docket_datetime)
  }
  if (typeof data.to_process_datetime === 'string') {
    o.to_process_datetime = moment(data.to_process_datetime)
  }
  if (typeof data.arbitrator_assign_datetime === 'string') {
    o.arbitrator_assign_datetime = moment(data.arbitrator_assign_datetime)
  }
  if (typeof data.arbitrator_assign0_datetime === 'string') {
    o.arbitrator_assign0_datetime = moment(data.arbitrator_assign0_datetime)
  }
  if (typeof data.closure_standard_datetime === 'string') {
    o.closure_standard_datetime = moment(data.closure_standard_datetime)
  }
  c.setFieldsValue(o)
}

async function submitHandle (data: { [k: string]: any }, hide: () => void, refreshData: () => void): Promise<void> {
  const id: string = data.id
  delete data.id
  const o = { ...data }
  if (data.accept_datetime instanceof moment) {
    o.accept_datetime = (data.accept_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  if (data.docket_datetime instanceof moment) {
    o.docket_datetime = (data.docket_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  if (data.to_process_datetime instanceof moment) {
    o.to_process_datetime = (data.to_process_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  if (data.arbitrator_assign_datetime instanceof moment) {
    o.arbitrator_assign_datetime = (data.arbitrator_assign_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  if (data.arbitrator_assign0_datetime instanceof moment) {
    o.arbitrator_assign0_datetime = (data.arbitrator_assign0_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  if (data.closure_standard_datetime instanceof moment) {
    o.closure_standard_datetime = (data.closure_standard_datetime as Moment).format('YYYY-MM-DD HH:mm:ss')
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateCaseRequest(id, o))
  h()
  if (e === null) {
    message.success('更新成功').then(null, null)
    hide()
    refreshData()
  }
}

interface Props {
  visible: boolean
  data: CaseSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [treeData, setTreeData] = useState<DataNode[]>([])
  const [persons, setPersons] = useState<string[]>([])
  const [types, setTypes] = useState<DictionaryItem[]>([])
  const [procedures, setProcedures] = useState<DictionaryItem[]>([])
  useEffect(() => {
    initTree(setTreeData).catch(e => console.error(e))
    initPersonList(setPersons).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const d = new Dictionary()
    d.init('结案类型,仲裁程序')
      .then(() => {
        setTypes(d.getList('结案类型'))
        setProcedures(d.getList('仲裁程序'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initForm(formRef, data)
  }, [data, formRef])
  return (
    <Modal title='编辑' width={1200} visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '158px' }} onFinish={async d => await submitHandle(d, hide, refreshData)}>
        <Item noStyle name='id'><span /></Item>
        <Row gutter={24}>
          <Col span={12}>
            <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='申请人' name='applicant_name'>
              <Input placeholder='多个申请人中文逗号分隔' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='被申请人' name='respondent_name'>
              <Input placeholder='多个被申请人中文逗号分隔' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='案由' name='cause_action'>
              <TreeSelect treeData={treeData} placeholder='请选择' showSearch />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='标的额' name='dispute_amount'>
              <UnitNumberInput unit='万元' precision={2} placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='增加标的额' name='dispute_amount_add'>
              <UnitNumberInput unit='万元' precision={2} placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='反请求标的额' name='dispute_amount_add'>
              <UnitNumberInput unit='万元' precision={2} placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='收案日期' name='accept_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='立案日期' name='docket_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='受理秘书' name='accepter'>
              <Select placeholder='请选择' showSearch allowClear>
                {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={12}>
            <Item label='移交办案秘书日期' name='to_process_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='第一次组庭日期' name='arbitrator_assign_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='最后一次组庭日期' name='arbitrator_assign0_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='实际结案日期' name='closure_standard_datetime'>
              <DatePicker style={{ width: '100%' }} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='结案方式' name='closure_type'>
              <Select placeholder='请选择'>
                {
                  types.map((li, i) => {
                    return <Option key={i} value={li.value}>{li.title}</Option>
                  })
                }
              </Select>
            </Item>
          </Col>
          <Col span={12}>
            <Item label='办案秘书' name='processer'>
              <Select placeholder='请选择' showSearch allowClear>
                {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={12}>
            <Item label='首席仲裁员' name='arbitrator'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='边裁一' name='arbitrator1'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='边裁二' name='arbitrator2'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={12}>
            <Item label='适用程序' name='procedure'>
              <Select placeholder='请选择'>
                {
                  procedures.map((li, i) => {
                    return <Option key={i} value={li.value}>{li.title}</Option>
                  })
                }
              </Select>
            </Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}

export default Main
